import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ]
  },
  mutations: {
    setallcheck (state, payload) {
      state.goodList.forEach(item => {
        item.checked = payload
      })
    },
    subNum (state, payload) {
      state.goodList[payload].num--
    },
    addNum (state, payload) {
      state.goodList[payload].num++
    },
    removeItem (state, payload) {
      state.goodList.splice(payload, 1)
    },
    setCheck (state, payload) {
      state.goodList[payload].checked = !state.goodList[payload].checked
    },
    addList (state, payload) {
      state.goodList.push(payload)
    }
  },
  actions: {},
  getters: {
    allCheck (state) {
      return state.goodList.every(item => {
        return item.checked
      })
    },
    totalPrice (state) {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) return (sum += item.num * item.price)
        return sum
      }, 0)
    }
  }
})
